package com.beney.service;

import com.beney.common.Identity;
import com.beney.dao.UserDao;
import com.beney.dao.UserDaoFactory;
import com.beney.util.Commands;
import com.beney.util.math.AbstractMath;
import com.beney.util.math.JuniorMath;
import com.beney.util.math.PrimaryMath;
import com.beney.util.math.SeniorMath;

import java.util.Random;
import java.util.Set;

/**
 *
 * @author Beney
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao;

    @Override
    public void setIdentity(String identity) {
        userDao.setIdentity(identity);
    }

    @Override
    public String getIdentity() {
        return userDao.getIdentity();
    }

    @Override
    public String getName()
    {
        return userDao.getName();
    }

    @Override
    public void generateQues(int numberOfQues) {
        System.out.print(Commands.wrapHintCommand("UserService 生成试卷中..."));
        String path = doGenerate(numberOfQues);
        if (path != null)
            System.out.println(Commands.wrapHintCommand(
                    "生成成功，文件已经保存在你的个人文件夹, ",
                    "地址:\n   ",
                    path
            ));
    }

    @Override
    public boolean initService(String name, String pwd) {
        return (userDao = UserDaoFactory.createUserDao(name, pwd)) != null;
    }

    /**
     * 生成题目并保存
     *
     * @param numberOfQues 题目总数
     * @return 题目保存到的文件路径；null-保存失败
     */
    private String doGenerate(int numberOfQues) {
        Set<Integer> quesCodes = userDao.getUserGeneratedQuesCodes();
        StringBuilder[] ques = new StringBuilder[numberOfQues];
        StringBuilder aQue;
        AbstractMath generator;
        String id;

        if ((id = userDao.getIdentity()).equals(Identity.XIAO_XUE))
            generator = PrimaryMath.getGenerator();
        else if (id.equals(Identity.CHU_ZHONG))
            generator = JuniorMath.getGenerator();
        else
            generator = SeniorMath.getGenerator();

        Random ran = new Random();
        for (int i = 0; i < numberOfQues; ++i) {
            aQue = generator.createEquation(ran.nextInt(5) + 1);
            if (quesCodes.contains(aQue.hashCode()))
                i--;    // try again
            else
                ques[i] = aQue;
        }
        return userDao.saveTestPaper(ques);
    }
}
